import { PageContainer } from '@ant-design/pro-layout';
import { Button, message, Tree, TreeSelect } from 'antd';
import {  useIntl } from 'umi';
import { DrawerForm, ProFormText, ProFormSelect, ProFormDigit, ProFormTextArea, ProFormSwitch } from '@ant-design/pro-form';
import React, { useState, useRef } from 'react';
import { addMenu, editMenu, findMenu, removeMenu,findMenuById} from '../service';




export default (): React.ReactNode => {
    const intl = useIntl();
    //表头信息以及表值设置
    const [editModel, setEditModel] = useState<any>();
    const [showCreate, setShowCreate] = useState(false);
    const [pidValue,setPidValue]  = useState<String>("0");
    const formRef = useRef<any>();
    const [treeData,setTreeData] = useState([]);
    const [allTreeData,setAllTreeData] = useState([]);

    React.useEffect(()=>{
      requestCourse();
      return function cleanup() {};
    },[]);
  
    const requestCourse=async()=>{
      var val = await findMenu({});
      if(val.errorCode=='200'){
        const mapTree = (org:any) => {
          const haveChildren = Array.isArray(org.child) && org.child.length > 0;
          return {
            key : org.id,
            value : String(org.id),
            title: org.name,
            children:haveChildren ? org.child.map((i:any) => mapTree(i)) : [],
          }
        };
        let arr:any = []
        arr = val.data.map((org:any) => mapTree(org) )
        setTreeData(arr);
 
        var all:any = [{'title':"顶级",key:'0',value:'0',pid:'0',children:arr}];
        console.log(all)
        setAllTreeData(all);
      }
    }
  
    const onSelect = async(selectedKeys:any, info:any) => {
      if(info.node.children.length==0){
        //最底层
      }else{
        //更改
      }
      var val = await findMenuById({"id":info.node.value})
      if(val.errorCode==='200'){
        setEditModel(val.data);
        setShowCreate(true)
        setPidValue(String(val.data.parentMenuId));
      }else{
        message.error('获取详情失败')
      }
    };
  
    const onChange = (value:any) => {
      console.log(value);
      setPidValue(value);
    };
  
    return (
      <PageContainer>
          <Button type="primary" style={{marginBottom:10}} key="add" onClick={()=>{
            setEditModel(undefined)
            setShowCreate(true)
          }}>新建</Button>
          {treeData.length>0?
          <Tree
            showLine={true}
            onSelect={onSelect}
            treeData={treeData}
            defaultExpandAll={true}
          />:<></>
          }
      <DrawerForm
              title="菜单编辑"
              formRef={formRef}
              onVisibleChange={v=>{
               setShowCreate(v)
               if(!v){
                 setEditModel(undefined)
                 setPidValue("0")
               }
              }}
              drawerProps={{
                destroyOnClose:true,
                forceRender:true
              }}
              visible={showCreate}
              onFinish={async (values: any) => {
                if(editModel){
                  values.id = editModel.id;
                }
                values.parentMenuId = pidValue;
                values.isActive = values.isActive?'1':'0'
                var val=null;
                if(editModel){
                  val = await editMenu(values);
                }else{
                  val = await addMenu(values);
                }
                if(val.errorCode==='200'){
                  await requestCourse();
                  return true;
                }else{
                  message.error('提交失败')
                  return false;
                }
              }}
           >
             <div>父级</div>
             {
               allTreeData.length>0?<TreeSelect
               style={{ width: '100%',marginBottom:10,marginTop:10 }}
               value={pidValue}
               dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
               treeData={allTreeData}
               placeholder="请选择"
               treeDefaultExpandAll
               onChange={onChange}
             />:<></>
             }  
            
            <ProFormText name="menuName" label="菜单名称" initialValue={editModel?.menuName}/>
            <ProFormText name="menuShortName" label="菜单简称" initialValue={editModel?.menuShortName}/>
            <ProFormText name="menuPath" label="菜单路径" initialValue={editModel?.menuPath}/>
            <ProFormText name="icon" label="图标名" initialValue={editModel?.icon}/>
            <ProFormDigit name="sortNum" label="排序" initialValue={editModel?.sortNum}/>
            <ProFormSwitch name="isActive" label="是否启用" initialValue={()=>{
                if(editModel){
                    return true
                }
                return editModel?.isActive==='1'
            }}/>
           
            {editModel?<Button type="default" onClick={async()=>{
              var val = await removeMenu({id:editModel.id});
              if(val.errorCode==='200'){
                await requestCourse();
                setShowCreate(false)
              }else{
                message.error('删除失败')
              }
            }}>删除</Button>:<></>}
        </DrawerForm>
      </PageContainer>
    );
  };
  